<template>
    <div class="publicpageview">
        <div class="publicformview">
            <el-form :inline="true" :model="listQuery" size="mini" ref="searchForm">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item label="角色名称：" prop="keyword">
                            <el-input v-model="listQuery.keyword"></el-input>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="4">
                        <el-form-item label="电话号码：" prop="phone">
                            <el-input v-model="listQuery.phone"></el-input>
                        </el-form-item>
                    </el-col>  -->
                    <el-col :span="4">
                        <el-form-item label="状态：" prop="status">
                            <el-select v-model="listQuery.status" clearable>
                                <el-option label="启用" value="0" key="1"></el-option>
                                <el-option label="禁用" value="1" key="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <div>
                            <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
                            <el-button size="mini" @click="resetForm('searchForm')">重置</el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <div class="publitableview">
            <el-button type="primary" size="mini" @click="handleAddUser('add')">新增角色</el-button>
            <el-table :data="list" border fit highlight-current-row size="mini">
                <el-table-column align="center" label="角色编号" prop="id">
                </el-table-column>
                <el-table-column align="center" label="角色名称" prop="name">
                </el-table-column>
                <!-- <el-table-column align="center" label="电话号码" prop="phone">
                </el-table-column> -->
                <el-table-column align="center" label="状态" prop="status">
                    <template slot-scope="scope">
                        <span>{{ scope.row.status == 0 ? "禁用" : "启用" }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="handleUpdate(scope.row, 'quanxian')">权限控制</el-button>
                        <el-button type="text" size="mini" @click="handleUpdate(scope.row, 'update')">修改</el-button>
                        <el-button type="text" size="mini" @click="handleUpdate(scope.row,'details')">详情</el-button>
                        <el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="publicpaginationview">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="listQuery.pageNum" background :page-sizes="[10, 20, 50, 100]"
                    :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    small></el-pagination>
            </div>
        </div>

        <el-dialog :title="isAdd == 'add' ? '新增角色' : isAdd == 'update' ? '修改角色' : isAdd == 'quanxian' ? '权限控制' : '角色详情'"
            :visible.sync="dialogVisible" width="40%" :before-close="handleClose">
            <el-form :model="formData" ref="dataForm" class="demo-ruleForm" label-position="right" label-width="120px"
                size="mini">
                <el-form-item label="角色编号：" prop="id">
                    <el-input v-model="formData.id" disabled></el-input>
                </el-form-item>
                <el-form-item label="用户名称：" prop="name">
                    <el-input v-model="formData.name" :disabled="isAdd == 'quanxian'"></el-input>
                </el-form-item>

                <!-- <el-form-item label="电话号码：" prop="phone">
                    <el-input v-model="formData.phone" :disabled="isAdd == 'quanxian'"></el-input>
                </el-form-item> -->
                <el-form-item label="状态：" prop="status">
                    <el-select v-model="formData.status" :disabled="isAdd == 'quanxian'">
                        <el-option label="启用" value="1" key="1"></el-option>
                        <el-option label="禁用" value="0" key="0"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="备注：" prop="remarks">
                    <el-input v-model="formData.remarks" type="textarea" :rows="2"
                        :disabled="isAdd == 'quanxian'"></el-input>
                </el-form-item>
            </el-form>

            <div class="treeview" v-if="isAdd == 'quanxian'">
                <span>权限控制： </span>
                <div style="flex: 1;">
                    <el-checkbox v-model="checkAll" @change="handleCheckAllChange"
                        :indeterminate="isIndeterminate">全选/全不选</el-checkbox>
                    <div class="tree">
                        <el-tree ref="tree" node-key="path" show-checkbox :data="treeData" :props="defaultProps"
                            @check="handleCheckChange" :default-checked-keys="checkedList">
                            <template #default="{ node, data }">
                                {{ data.meta.title}}

                            </template>
                        </el-tree>
                    </div>
                </div>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleClose" size="medium" v-if="isAdd == 'details'">返
                    回</el-button>

                <el-button type="primary" @click="handleSubmitClick" size="medium" v-else>保 存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
let arr = [];
let treeArr = [];
import { listAll, deleteRole, createRole, allResourceRole, updateRole } from '@/api/system'
import { listResource, allocResource } from '@/api/index'
import { Message } from 'element-ui'
export default {
    name: "AccommodationManagementIndex",

    data() {
        return {
            listQuery: {
                pageNum: 1,
                pageSize: 10,
                keyword: "",
                status: "",
                // phone: "",
            },
            checkedList: [], //当前选择的树keys

            total: 0,
            options: [{ key: "1" }],
            list: [

            ],
            isIndeterminate: false,

            dialogVisible: false,
            isAdd: 'add',
            formData: {
                id: "",
                name: "",
                status: "",
                // phone: "",
                remarks: "",
            },

            defaultProps: {
                children: 'children',
                label: 'name'
            },

            checkAll: false,

            treeData: [],
        };
    },

    computed: {

    },

    mounted() {
        this.getList();


        this.getAllCheckKeys([...this.$router.options.routes[0].children]);
        this.treeData = this.filterHiddenRoutes([...this.$router.options.routes[0].children]);

    },

    beforeDestroy() {
        arr = []
    },

    methods: {


        filterHiddenRoutes(routes) {
            return routes.filter(route => {
                if (route.children) {
                    route.children = this.filterHiddenRoutes(route.children)
                }
                return !route.meta?.isHide
            })
        },
        handleSubmitClick() {
            const { formData } = this;
            if (this.isAdd == 'add') {
                createRole({ ...formData }).then(res => {
                    this.handleClose();
                    this.getList();
                    Message({
                        message: res.message || '操作成功',
                        type: "success",
                        duration: 5 * 1000,
                    });
                })
            }
            if (this.isAdd == 'update' || this.isAdd == 'details') {
                updateRole({ ...formData }).then(res => {
                    this.handleClose();
                    this.getList();
                    Message({
                        message: res.message || '操作成功',
                        type: "success",
                        duration: 5 * 1000,
                    });
                })
            }
            if (this.isAdd == 'quanxian') {
                let formdata = new FormData();
                formdata.append('roleId', formData.id);
                formdata.append('resourceIds', this.checkedList.join(','));

                allocResource(formdata).then(res => {
                    this.handleClose();
                    this.getList();
                    Message({
                        message: res.message || '操作成功',
                        type: "success",
                        duration: 5 * 1000,
                    });
                })
            }
        },

        getAllCheckKeys(option) {
            option.forEach(item => {

                if (item.meta.isHide != true) {
                    arr.push(item.path)
                }

                if (item.children) {
                    this.getAllCheckKeys(item.children)
                }
            })

        },
        handleSizeChange(val) {
            this.listQuery.pageNum = 1;
            this.listQuery.pageSize = val;
            this.getList();
        },
        handleCurrentChange(val) {
            this.listQuery.pageNum = val;
            this.getList();
        },

        handleSearch() {
            this.listQuery.pageNum = 1;
            this.getList();
        },
        getList() {
            listAll(this.listQuery).then((response) => {
                this.list = response.data.list;
                this.total = response.data.total;
            });
        },

        handleCheckChange(data, checked) {

            console.log(arr.length, checked)
            this.checkedList = checked.checkedKeys;
            console.log(this.checkedList.length)
            if (arr.length == 0) {
                this.checkAll = false;
                this.isIndeterminate = false;
            } else {
                if (this.checkedList.length == 0) {
                    this.checkAll = false;
                    this.isIndeterminate = false;
                } else {

                    if (arr.length == this.checkedList.length) {

                        this.checkAll = true;
                        this.isIndeterminate = false;
                    }
                    if (arr.length > this.checkedList.length) {


                        this.checkAll = false;
                        this.isIndeterminate = true;
                    }
                }


            }
        },

        setCheckStatus(id) {

            listResource(id).then(res => {
                this.checkedList = res.data.map(item => item.path)
                if (arr.length != 0) {
                    if (this.checkedList.length != 0) {

                        console.log(arr.length, this.checkedList.length)
                        if (this.checkedList.length == arr.length) {
                            console.log('1')
                            this.checkAll = true;
                            this.isIndeterminate = false;
                            this.$refs.tree.setCheckedKeys(arr);
                        } else {
                            this.checkAll = false;
                            this.isIndeterminate = true;
                            this.$refs.tree.setCheckedKeys(this.checkedList);
                        }
                    } else {
                        this.checkAll = false;
                        this.isIndeterminate = false;
                    }
                } else {
                    this.checkAll = false;
                    this.isIndeterminate = false;
                }
            })


        },

        handleCheckAllChange() {
            if (arr.length != 0) {
                if (this.checkedList.length != 0) {
                    if (this.checkedList.length == arr.length) {
                        this.checkAll = false;
                        this.$refs.tree.setCheckedKeys([]);
                        this.checkedList = []
                    } else {
                        this.checkAll = true;
                        this.isIndeterminate = false;
                        this.$refs.tree.setCheckedKeys(arr);
                        this.checkedList = arr;
                    }
                } else {
                    this.checkAll = true;
                    this.isIndeterminate = false;
                    this.$refs.tree.setCheckedKeys(arr);
                    this.checkedList = arr;
                }
            } else {
                this.checkAll = false;
                this.isIndeterminate = false;
            }
        },
        resetForm(val) {

            this.$refs[val].resetFields();
            this.listQuery.pageNum = 1;
        },

        handleAddUser(type) {
            this.isAdd = 'add';
            this.dialogVisible = true;
            this.checkedList = [];
            // this.$nextTick(() => {
            //     this.$refs.tree.setCheckedKeys([]);
            // })

            // this.checkAll = false;
            // this.isIndeterminate = false;
        },

        handleClose() {
            this.resetForm("dataForm");
            this.dialogVisible = false;
        },

        handleUpdate(currentData, type) {
            this.isAdd = type;
            //   一定要在打开弹窗前 再赋值 不然resetFiles没用
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.formData = { ...currentData, status: String(currentData.status) };
                if (this.isAdd == 'quanxian') {
                    this.setCheckStatus(currentData.id);
                }
            });
        },

        handleDelete(id) {
            this.$confirm(
                "此操作将删除该条内容，请确认是否继续操作？",
                "删除提示",
                {
                    confirmButtonText: "保 存",
                    cancelButtonText: "取 消",
                    type: "warning",
                }
            )
                .then(() => {
                    deleteRole(id).then(res => {
                        Message({
                            message: res.message || '操作成功',
                            type: "success",
                            duration: 5 * 1000,
                        });
                        this.getList();
                    })
                })
                .catch(() => { });
        }
    },
};
</script>

<style scoped>
.treeview {
    width: 100%;
    background: #F7F7F7;
    display: flex;
    padding-bottom: 20px;
    padding-top: 20px;

    span {
        color: #008c93;
        width: 120px;
        text-align: right;
        display: inline-block;
        /* margin-right: 4px; */
        box-sizing: border-box;
        padding-right: 12px;
    }

    margin-top: 20px;
}

.tree {
    background: #FFFFFF;
    margin-top: 10px;
}
</style>